import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:paly_android/api/api.dart';
import 'package:paly_android/bean/article_data_entity.dart';
import 'package:paly_android/bean/wxartilce_type_entity.dart';
import 'package:paly_android/net/dio_client.dart';

part 'wx_article_event.dart';

part 'wx_article_state.dart';

class WxArticleBloc extends Bloc<WxArticleEvent, WxArticleState> {
  WxArticleBloc() : super(WxArticleInitial());

  @override
  Stream<WxArticleState> mapEventToState(
    WxArticleEvent event,
  ) async* {
    if (event is WxTypeEvent) {
      List<WxartilceTypeData> data =
          await DioClient.instance.get(Api.WXARTICLE);
      WxArticleInitial wxArticleDataState = WxArticleInitial();
      wxArticleDataState.data.addAll(data);
      yield wxArticleDataState;
    }

    if (event is WxOneTypeEvent) {
      ArticleDataEntity data = await DioClient.instance.get(Api.WXARTICLELIST
          .replaceFirst("typeId", event.typeId)
          .replaceFirst("page", event.page.toString()));

      WxArticleInitial wxArticleDataState = WxArticleInitial();
      WxArticleInitial _wxS = state as WxArticleInitial;
      if (event.isRefresh) {
        // _wxS.articles.clear();
        wxArticleDataState.articles.addAll(data.datas);
      } else {
        wxArticleDataState.articles.addAll(_wxS.articles);
        wxArticleDataState.articles.addAll(data.datas);
      }

      yield wxArticleDataState;
    }
  }
}
